-- SkyTowerM
-- created by chendh
-- 天空之城试练塔模块

module("SkyTowerM", package.seeall);

local skyTowerConfig = {};
local maxFloorConfig = {};
local towerFloorConfig = {};

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    skyTowerConfig = {};
    towerFloorConfig = {};

    -- 转换下sky_tower_CSV信息表
    local sky_tower_CSV = get_sky_tower_CSV();
    for i = 1, #sky_tower_CSV do
        local row = sky_tower_CSV[i];
        row.bonus = parseBonus(row.bonus);
        skyTowerConfig[row.id] = row;

        -- 统计下个阵营的试练塔最高楼层
        if row.floor > tonumber(maxFloorConfig[row.camp]) then
            maxFloorConfig[row.camp] = row.floor;
        end

        if not towerFloorConfig[row.camp] then
            towerFloorConfig[row.camp] = {};
        end

        towerFloorConfig[row.camp][row.floor] = row.id;
    end
end

-- 模块初始化操作
function init()
    loadCsv();

    EventMgr.removeAll("SkyTowerM");
end

-- 解析奖励
function parseBonus(bonus)
    local data = {};
    local arr = string.explode(string.sub(bonus, 3, -2), ",");
    local classId = arr[1];

    if tonumber(arr[1]) > 0 then
        classId = tonumber(arr[1]);
    end
    if string.startWith(bonus, "1(") then
        data = { 1, classId, tonumber(arr[2]), };
    elseif string.startWith(bonus, "2(") then
        data = { 2, classId, tonumber(arr[2]), };
    elseif string.startWith(bonus, "6(") then
        data = { 6, classId, tonumber(arr[2]), };
    elseif string.startWith(bonus, "8(") then
        data = { 8, classId, tonumber(arr[2]), };
    end

    return data;
end

-- 检索
function query(id, path)
    local m = skyTowerConfig[id];

    if not m or not path then
        return m;
    end

    return m[path];
end

-- 获取阵营的最高楼层
function getMaxFloor(camp)
    return maxFloorConfig[camp] or 0;
end

-- 获取指定阵营指定楼层的试炼id
function getTowerId(camp, floor)
    if not towerFloorConfig[camp] then
        return 0;
    else
        return towerFloorConfig[camp][floor] or 0;
    end
end

-- 获取试炼进度
function getProgress(camp)
    local skyTower = ME.user.dbase:query("sky_tower") or {};

    if not skyTower[camp] then
        return 0;
    else
        return skyTower[camp]["floor"] or 0;
    end
end

-- 获取奖励领取进度
function getBonusProgress(camp)
    local skyTower = ME.user.dbase:query("sky_tower") or {};

    if not skyTower[camp] then
        return 0;
    else
        return skyTower[camp]["bonus"] or 0;
    end
end

-- 获取指定阵营未领取的奖励数量
function getAvailableBonuNum(camp)
    local curProgress = getProgress(camp);
    local bonusProgress = getBonusProgress(camp);

    if curProgress > bonusProgress then
        return curProgress - bonusProgress;
    else
        return 0;
    end
end

-- 发起试炼
function tryToStartFight()
    local ret = canFight();
    if ret == true then
        Operation.cmd_tower_start_fight();
    end

    return ret;
end

-- 判断是否可以发起试炼
function canFight()
    local camp = ME.user.dbase:query("activedSkyGroup");
    local curFloor = getProgress(camp);
    local maxFloor = getMaxFloor(camp);

    if curFloor >= maxFloor then
        return "tower_is_finshed";
    end

    return true;
end

-- 尝试领取奖励
function tryToFetchBonus(camp)
    local ret = canFetchBonus(camp);
    if ret == true then
        local curBonusFloor = getBonusProgress(camp);
        local id = getTowerId(camp, curBonusFloor + 1);
        local bonus = query(id, "bonus");

        -- 先修改数据
        local skyTower = ME.user.dbase:query("sky_tower") or {};
        skyTower[camp]["bonus"] = curBonusFloor + 1;

        -- 奖励
        BonusM.doBonus(bonus, "sky_tower_bonus");

        -- 抛出试练塔奖励领取事件
        EventMgr.fire(event.SKY_TOWER_BONUS, { ["floor"] = curBonusFloor + 1, ["bonus"] = bonus });

        -- 发消息通知服务器
        Operation.cmd_tower_fetch_bonus(camp);
    end

    return ret;
end

-- 判断是否可以领取奖励
function canFetchBonus(camp)
    local skyTower = ME.user.dbase:query("sky_tower") or {};

    if not skyTower[camp] then
        return "no_reward";
    end

    if tonumber(skyTower[camp]["bonus"]) >= tonumber(skyTower[camp]["floor"]) then
        return "no_reward";
    end

    return true;
end

-- 通知试炼结果
function notifyFightResult(result)
    -- TODO: 奖励格式需要转下
    local bonus;
    if result.bonus then
        local temp = result.bonus;
        if type(temp[1]) == "number" then
            bonus = { temp, };
        else
            bonus = {};
            for index, arr in pairs(temp) do
                bonus[index] = arr;
            end
        end
    end
    result.bonus = bonus;

    -- 战斗
    local ret = result.result;
    local attackerInfo = result.attacker;
    local defenserInfo = result.defenser;
    local record = result.record;
    local bonus = result.bonus;

    -- 创建一个战场
    SkyCombatM.createBattle(attackerInfo, defenserInfo, ret, record, bonus);

    EventMgr.fire(event.SKY_TOWER_RESULT, { ["result"] = result, });
end

-- 获得某一层的奖励信息
function getCurBonus(camp, floor)
    local towerId = getTowerId(camp, floor);
    local bonus = query(towerId, "bonus") or {};

    if bonus[1] == 1 and SkyRelicFunctionM.itemIsSkyMedal(bonus[2]) then
        if not SkyRelicFunctionM.isServerSkyMedalOpen() then
            bonus = FormulaM.invoke("CALC_BACKUP_SKY_TOWER_BONUS", camp);
        end
    end

    return bonus;
end